package cn.itcast.controller;

import cn.itcast.constant.MessageConstant;
import cn.itcast.constant.RedisMessageConstant;
import cn.itcast.entity.Result;
import cn.itcast.pojo.Order;
import cn.itcast.service.OrderService;
import cn.itcast.utils.SMSUtils;
import com.alibaba.dubbo.config.annotation.Reference;
import com.github.pagehelper.util.StringUtil;
import com.qiniu.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.swing.*;
import java.util.Map;

/**
 * @version V1.0
 * @author: luoqianjin
 * @date: 2019/8/2 17:05
 * @description:
 */
@RestController
@RequestMapping("order")
public class OrderController {
    @Reference
    private OrderService orderService;
    @Autowired
    private JedisPool jedisPool;

    /**
     * 提交预约
     *
     * @return
     */
    @RequestMapping("submit")
    public Result submit(@RequestBody Map map) throws Exception {
        //0.获取前端穿过来的信息
        String validateCode = map.get("validateCode").toString();
        String telephone = map.get("telephone").toString();
        String orderDate = map.get("orderDate").toString();

        //1.验证码校验
        String codeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (StringUtil.isEmpty(codeInRedis) || !validateCode.equals(codeInRedis)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
        // 2.验证码没问题的情况下，通过服务新增预约
        map.put("order_type", Order.ORDERTYPE_WEIXIN);
        Result result = orderService.submit(map);

        // 3.发送短信，提示用户预约成功
        try {
            SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, orderDate);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 根据id查询预约信息，包括套餐信息和会员信息
     */
    @RequestMapping("findById")
    public Result findById(Integer id) {
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
